package springboot.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

public class NettySer {

    public void start(Integer port) throws Exception {

        System.out.println("准备开启服务");
        //服务端要建立两个group，一个负责接收客户端的连接，一个负责处理数据传输
        //连接处理group
        EventLoopGroup boss = new NioEventLoopGroup();
        //事件处理group
        EventLoopGroup work = new NioEventLoopGroup();
        //创建ServerBootstrap实例
        ServerBootstrap b = new ServerBootstrap();
        b.group(boss,work)
                //设置将要被实例化的ServerChannel类
                .channel(NioServerSocketChannel.class)
                //设置服务端用于通信的端口号
                .localAddress(new InetSocketAddress(port))
                //设置处理数据的类
                //IdleStateHandler这个类会根据你设置的超时参数的类型和值，
                //循环去检测channelRead和write方法多久没有被调用了，如果这个时间超过了你设置的值，那么就会触发对应的事件，
                //read触发read，write触发write，all触发all[TimeUnit.SECONDS]单位秒
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new IdleStateHandler(2,2,2, TimeUnit.SECONDS));

                        ch.pipeline().addLast(new SimpleServerHandler());
                    }
                });

        //log.info("Loading springboot.netty . . .");
        System.out.println("服务开启中...");
        //绑定端口后，开启监听
        ChannelFuture channelFuture = b.bind().sync();
        System.out.println("开启的状态是"+channelFuture.isSuccess());
        if (channelFuture.isSuccess()){
            System.out.println("开启成功!!!");
        }
    }
}
